import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../utils/http_helper.dart';
import 'home_first_screen.dart';
import 'home_item.dart';
import '../../providers/scroll_provider.dart';
import 'model/home_banner_model.dart';

class HomeIndexScrren extends ConsumerStatefulWidget {
  const HomeIndexScrren({super.key});

  @override
  ConsumerState<HomeIndexScrren> createState() => _HomeIndexScrrenState();
}

class _HomeIndexScrrenState extends ConsumerState<HomeIndexScrren>
    with TickerProviderStateMixin {
  // 改为 TickerProviderStateMixin
  late TabController _tabController;
  late PageController _pageController;
  int _currentIndex = 0;

  // 添加状态变量
  List<HomeBannerModel> _categories = [];
  bool _isLoading = true;
  bool _hasError = false;
  int _retryCount = 0; // 添加重试计数器
  static const int _maxRetries = 3; // 最大重试次数

  // 动态生成页面列表
  List<Widget> get _pages {
    if (_categories.isEmpty) {
      return [const HomeFirstScrren(categoryId: '')];
    }

    return _categories.asMap().entries.map((entry) {
      final index = entry.key;
      final category = entry.value;
      final categoryId = category.id ?? '';

      // 第一个页面使用 HomeFirstScrren，其他使用 HomeContentWidget
      if (index == 0) {
        return HomeFirstScrren(categoryId: categoryId);
      } else {
        return HomeContentWidget(isFirst: false, categoryId: categoryId);
      }
    }).toList();
  }

  // 动态生成的标签
  List<Tab> get _tabs {
    if (_categories.isEmpty) {
      return [const Tab(text: 'For You')]; // 默认标签
    }
    return _categories
        .map((category) => Tab(text: category.title ?? 'Unknown'))
        .toList();
  }

  Future<void> _getCategoryData() async {
    try {
      setState(() {
        _isLoading = true;
        _hasError = false;
      });

      final userResponse = await HttpUtil().getModel<List<HomeBannerModel>>(
        'Comic/GetComicCategoriesList',
        fromJson: (json) => (json as List)
            .map((item) => HomeBannerModel.fromJson(item))
            .toList(),
      );

      if (userResponse?.status == 200 && userResponse?.result != null) {
        final banners = userResponse!.result!;
        // 需要过滤banners的数据，只保留type为1的
        final filteredBanners =
            banners.where((banner) => banner.type == 1).toList();

        // 先保存旧的 TabController
        final oldTabController = _tabController;

        // 创建新的 TabController
        final newTabController =
            TabController(length: filteredBanners.length, vsync: this);

        setState(() {
          _categories = filteredBanners;
          _isLoading = false;
          _retryCount = 0; // 重置重试计数器
          // 替换为新的 TabController
          _tabController = newTabController;
        });

        // 在下一帧释放旧的 TabController
        WidgetsBinding.instance.addPostFrameCallback((_) {
          oldTabController.dispose();
        });
      } else {
        print("Failed to get categories, status: ${userResponse?.status}");
        await _handleApiFailure();
      }
    } catch (e) {
      print("Error getting categories: $e");
      await _handleApiFailure();
    }
  }

  // 处理API请求失败的方法
  Future<void> _handleApiFailure() async {
    if (_retryCount < _maxRetries) {
      _retryCount++;
      print("Retrying API request, attempt $_retryCount/$_maxRetries");

      // 等待1秒后重试
      await Future.delayed(const Duration(seconds: 1));
      await _getCategoryData();
    } else {
      print("Max retries reached, showing error state");
      setState(() {
        _isLoading = false;
        _hasError = true;
      });
    }
  }

  // 手动重试方法（用于重新加载按钮）
  void _manualRetry() {
    _retryCount = 0; // 重置重试计数器
    _getCategoryData();
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 1, vsync: this); // 初始长度为1
    _pageController = PageController(initialPage: 0);

    _getCategoryData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  // 构建无数据占位图
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.wifi_off_outlined,
            size: 80,
            color: Colors.white.withOpacity(0.3),
          ),
          const SizedBox(height: 16),
          Text(
            'Failed to load categories',
            style: TextStyle(
              color: Colors.white.withOpacity(0.6),
              fontSize: 16,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'Tried $_maxRetries times, please check your network connection',
            style: TextStyle(
              color: Colors.white.withOpacity(0.4),
              fontSize: 14,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _manualRetry,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF8A7CA8),
              foregroundColor: Colors.white,
            ),
            child: const Text('Retry'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 如果正在加载，显示加载指示器
    if (_isLoading) {
      return const Scaffold(
        backgroundColor: const Color(0xFF211839),
        body: const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
          ),
        ),
      );
    }

    // 如果有错误或无数据，显示占位图
    if (_hasError || _categories.isEmpty) {
      return Scaffold(
        backgroundColor: const Color(0xFF211839),
        body: _buildEmptyState(),
      );
    }

    return Scaffold(
      // appBar: AppBar(
      //   backgroundColor: Colors.transparent,
      //   elevation: 0,
      //   systemOverlayStyle: const SystemUiOverlayStyle(
      //     statusBarColor: Colors.transparent,
      //     statusBarIconBrightness: Brightness.light,
      //     statusBarBrightness: Brightness.dark,
      //   ),
      // ),
      extendBodyBehindAppBar: true,
      body: Stack(
        children: [
          // 主内容区 - 可左右滑动的页面
          PageView(
            controller: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
              if (index == 0) {
                setState(() {
                  _tabController.index = 0;
                });
              }
              _tabController.animateTo(index);
            },
            children: _pages,
          ),

          // 状态栏背景
          Consumer(
            builder: (context, ref, child) {
              final scrollOffset = ref.watch(scrollOffsetProvider);
              final opacity = _currentIndex == 0
                  ? (scrollOffset / 100).clamp(0.0, 1.0)
                  : 1.0;

              return Positioned(
                left: 0,
                right: 0,
                top: 0,
                child: Container(
                  color: Color(0xFF211839).withOpacity(opacity),
                  height: MediaQuery.of(context).padding.top,
                ),
              );
            },
          ),

          // 顶部标签栏
          Consumer(
            builder: (context, ref, child) {
              final scrollOffset = ref.watch(scrollOffsetProvider);
              final opacity = _currentIndex == 0
                  ? (scrollOffset / 100).clamp(0.0, 1.0)
                  : 1.0;

              return Positioned(
                top: MediaQuery.of(context).padding.top,
                left: 0,
                right: 0,
                height: 50,
                child: Container(
                  color: const Color(0xFF211839).withValues(alpha: opacity),
                  padding: const EdgeInsets.only(left: 16),
                  child: TabBar(
                    isScrollable: true,
                    tabAlignment: TabAlignment.start,
                    labelPadding: const EdgeInsets.only(left: 16, right: 8),
                    indicator: BoxDecoration(
                      color: Colors.transparent,
                      borderRadius: BorderRadius.circular(25),
                    ),
                    dividerColor: Colors.transparent,
                    controller: _tabController,
                    onTap: (index) {
                      _pageController.animateToPage(
                        index,
                        duration: const Duration(milliseconds: 300),
                        curve: Curves.ease,
                      );
                    },
                    tabs: _tabs,
                    labelColor: Colors.white,
                    unselectedLabelColor: Colors.white70,
                    unselectedLabelStyle: const TextStyle(fontSize: 15),
                    labelStyle: const TextStyle(
                        fontSize: 16, fontWeight: FontWeight.w600),
                    indicatorColor: Colors.white,
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
